<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="Stylesheet" type="text/css" href="style.css">
<title>Bubble Sort</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>

<h2 id="toc_0.1">Bubble Sort</h2>
<dl>
<dt>Stats</dt>
<dd>Worst Case Performance: O(n<sup><small>2</small></sup>)</dd>
<dd>Best Case Performance: O(n)</dd>
</dl>

<h3 id="toc_0.1.1">Optimized Psuedocode</h3>
<p>
Bubble Sort can be optimized by observing that the n-th pass finds the n-th largest element and puts it into its final place. So the inner loop can avoid looking at the last n-1 items when running for the n-th time.
</p>
<pre>
function bubbleSort(items) {
  n = count(items);
  swapped = false;
  while(!swapped) {
    swapped = false;
    for(i = 1; i &lt; n; i++) {
      if(items[i-1] &gt; items[i]) {
        tmp = items[i-1];
        items[i-1] = items[i];
        items[i] = tmp;
        swapped = true;
      }
    }
    n = n-1;
  }
}
</pre>


<h3 id="toc_0.1.2">Unoptimized Psuedocode</h3>
<pre>
function bubbleSort(items) {
  swapped = false;
  while(!swapped) {
    swapped = false;
    for(i = 1; i &lt; count(items); i++) {
      if(items[i-1] &gt; items[i]) {
        tmp = items[i-1];
        items[i-1] = items[i];
        items[i] = tmp;
        swapped = true;
      }
    }
  }
}
</pre>

<h3 id="toc_0.1.3">Additional Info</h3>
<p>
Wikipedia Article: [<a href="http://en.wikipedia.org/wiki/Bubble_sort]">http://en.wikipedia.org/wiki/Bubble_sort]</a>
</p>

</body>
</html>